package com.xin.ruanjian.omsystem.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.xin.ruanjian.omsystem.R;
import com.xin.ruanjian.omsystem.activity.LoginActivity;
import com.xin.ruanjian.omsystem.activity.ShopDetailActivity;
import com.xin.ruanjian.omsystem.adapter.GoodsLeftAdapter;
import com.xin.ruanjian.omsystem.adapter.GoodsRightAdapter;
import com.xin.ruanjian.omsystem.app.MyApplication;
import com.xin.ruanjian.omsystem.bases.BaseFragment;
import com.xin.ruanjian.omsystem.bases.Login;
import com.xin.ruanjian.omsystem.bean.DishBean;
import com.xin.ruanjian.omsystem.bean.GoodsBean;
import com.xin.ruanjian.omsystem.bean.MessageEvent;
import com.xin.ruanjian.omsystem.model.ShopCarModel;
import com.xin.ruanjian.omsystem.utils.GoodsAnimUtil;
import com.xin.ruanjian.omsystem.utils.HttpUtils;
import com.xin.ruanjian.omsystem.utils.ShopCarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmResults;
import okhttp3.Call;

import static com.xin.ruanjian.omsystem.bases.Contants.MENU_LIST;

/**
 * Created by local123 on 2018/2/20.
 */

public class GoodsFragment extends BaseFragment {
    @BindView(R.id.rv_goods_left)
    RecyclerView rvGoodsLeft;
    @BindView(R.id.rv_goods_right)
    RecyclerView rvGoodsRight;
    private String shopId;
    private GoodsLeftAdapter leftAdapter;
    private GoodsRightAdapter rightAdapter;
    private GoodsBean bean;

    private Login login = MyApplication.getLogin();
    private int currentMenuId;

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_goods, container, false);
    }

    @Override
    protected void initView(View view) {
        isNeedReload = false;
        leftAdapter = new GoodsLeftAdapter(context);
        rightAdapter = new GoodsRightAdapter(context);
        leftAdapter.setListener(new GoodsLeftAdapter.onMenuSelectListener() {
            @Override
            public void menuSelected(int position, int menuId) {
                currentMenuId = menuId;
                rightAdapter.setData(bean.getMsg().get(position).getDishList());
            }
        });
        rightAdapter.setListener(new GoodsRightAdapter.onItemClickListener() {
            @Override
            public void onAddClick(GoodsRightAdapter.ViewHolder holder, DishBean bean) {
                GoodsAnimUtil.setAnim(getActivity(), holder.ivShopDetailDishAdd, ((ShopDetailActivity)getActivity()).rlShopCarIcon);
                GoodsAnimUtil.setOnEndAnimListener(new onEndAnim());
                int num = bean.getNum() + 1;
                if (num == 1) {
                    holder.ivShopDetailDishSub.setAnimation(GoodsAnimUtil.getShowAnimation());
                    holder.tvShopDetailDishNum.setAnimation(GoodsAnimUtil.getShowAnimation());
                    holder.ivShopDetailDishSub.setVisibility(View.VISIBLE);
                    holder.tvShopDetailDishNum.setVisibility(View.VISIBLE);
                }
                bean.setNum(num);
                ShopCarUtils.updateShopCar(bean, bean.getNum(), login.getUserId());
            }

            @Override
            public void onSubClick(GoodsRightAdapter.ViewHolder holder, DishBean bean) {
                int num = bean.getNum() - 1;
                bean.setNum(num);
                ShopCarUtils.updateShopCar(bean, bean.getNum(), login.getUserId());
                ((ShopDetailActivity)getActivity()).updateShopCar();
            }
        });
        rvGoodsLeft.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        rvGoodsRight.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        rvGoodsLeft.setAdapter(leftAdapter);
        rvGoodsRight.setAdapter(rightAdapter);
        rvGoodsLeft.setItemAnimator(null);
        rvGoodsRight.setItemAnimator(null);
    }

    @Override
    protected void initData() {
        showLoadingDialog();
        initMenu();
    }

    public static GoodsFragment newInstance(String shopid) {
        GoodsFragment fragment = new GoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("shopid", shopid);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void initMenu() {
        //初始化
        HttpUtils httpUtils = new HttpUtils(MENU_LIST) {
            @Override
            public void onError(Call call, Exception e, int id) {
                showErrorDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "onResponse: " + response);
                hideLoadingDialog();
                try {
                    JSONObject o = new JSONObject(response);
                    int state = o.getInt("state");
                    if (state == 1) {
                        bean = new Gson().fromJson(response, GoodsBean.class);
                        leftAdapter.setData(bean.getMsg());
                        if (bean.getMsg() != null && !bean.getMsg().isEmpty()) {
                            currentMenuId = bean.getMsg().get(0).getMid();
                            rightAdapter.setData(bean.getMsg().get(0).getDishList());
                        }
                        updateAll(ShopCarUtils.getShopCarData(Integer.parseInt(shopId), login.getUserId()));
                    }else if (state == 9){
                        startActivity(new Intent(context, LoginActivity.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        if (login != null) {
            shopId = getArguments().getString("shopid", "");
            httpUtils.addParam("shopid", shopId);
            httpUtils.addParam("userid", login.getUserId()+"");
            httpUtils.addParam("token", login.getToken());
            httpUtils.clicent();
        }else {
            startActivity(new Intent(context, LoginActivity.class));
            getActivity().finish();
        }
    }

    /**
     * 动画结束后，更新所有数量和所有价格
     */
    class onEndAnim implements GoodsAnimUtil.OnEndAnimListener {
        @Override
        public void onEndAnim() {
            ((ShopDetailActivity)getActivity()).updateShopCar();
        }
    }

    public void updateMessage(ShopCarModel model, int num) {
        boolean isFind = false;
        if (bean != null) {
            for (int i=0;i<bean.getMsg().size();i++) {
                if (bean.getMsg().get(i).getMid() == model.getMid()) {
                    for (DishBean dishBean : bean.getMsg().get(i).getDishList()) {
                        if (dishBean.getDid() == model.getDid()) {
                            dishBean.setNum(num);
                            if (currentMenuId == model.getMid()) rightAdapter.notifyDataSetChanged();
                            isFind = true;
                        }
                    }
                }
            }
        }
        if (isFind) {
            ShopCarUtils.updateShopCar(model, num, login.getUserId());
        }else {
            ShopCarUtils.updateShopCar(model, 0, login.getUserId());
        }
    }

    public void updateAll(List<ShopCarModel> local) {
        for (ShopCarModel model : local) {
           updateMessage(model, model.getdNum());
        }
    }

    public void clearAll() {
        for (GoodsBean.MsgBean menu : bean.getMsg()) {
            for (DishBean dish : menu.getDishList()) {
                dish.setNum(0);
                if (currentMenuId == menu.getMid()) rightAdapter.notifyDataSetChanged();
            }
        }
    }
}
